package cz.tsystems.base;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import cz.tsystems.data.DataProvider;
import cz.tsystems.portablecheckin.*;
import android.app.ActionBar.Tab;
import android.app.ActionBar.TabListener;
import android.app.ActionBar;
import android.app.FragmentTransaction;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.content.LocalBroadcastManager;
import android.support.v4.view.ViewPager;
import android.text.format.Time;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;

public class FragmentPagerActivity extends FragmentActivity implements TabListener{
	
    ViewPager mViewPager;
    SectionsPagerAdapter mSectionsPagerAdapter;
    private Time stopTime;
    private BaseFragment theFragment;
    
    BroadcastReceiver receiver = new BroadcastReceiver() {
		
		@Override
		public void onReceive(Context context, Intent intent) {
//			Fragment f = getSupportFragmentManager().findFragmentByTag("mainFragment");
			Fragment f = mSectionsPagerAdapter.getFragment(getActionBar().getSelectedTab().getPosition());
			Log.d("FRAGMENT", f.getClass().getSimpleName() );
			((BaseFragment)f).showData(intent);			
		}
	};
    
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_fragment_pager);
		
        // Set up the action bar.
        final ActionBar actionBar = getActionBar();
        actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
        
        // Create the adapter that will return a fragment for each of the three
        // primary sections of the app.
        mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());        
        
        // Set up the ViewPager with the sections adapter.
        mViewPager = (ViewPager) findViewById(R.id.pager);// new ViewPager(this);
//        mViewPager.setId(R.id.pager);
//        setContentView(mViewPager);
        mViewPager.setAdapter(mSectionsPagerAdapter);
        
        // When swiping between different sections, select the corresponding
        // tab. We can also use ActionBar.Tab#select() to do this if we have
        // a reference to the Tab.
        mViewPager.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
            @Override
            public void onPageSelected(int position) {
                actionBar.setSelectedNavigationItem(position);
            }
            
        });

            actionBar.addTab(
                    actionBar.newTab().setText("Main").setTabListener(this));
            actionBar.addTab(
                    actionBar.newTab().setText("Body").setTabListener(this));            
            actionBar.addTab(
                    actionBar.newTab().setText("Service").setTabListener(this));
            actionBar.addTab(
                    actionBar.newTab().setText("Offers").setTabListener(this));            
        
	}
	
	private void registerRecaiver()
	{
        IntentFilter filterSend = new IntentFilter();
        filterSend.addAction("recivedData");
        LocalBroadcastManager.getInstance(this).registerReceiver(receiver, filterSend);
	}
	
	@Override
	protected void onStart() {
		if(stopTime != null)
		{
			Time now = new Time();
			now.setToNow();
			long backgroundTime = now.toMillis(true) - stopTime.toMillis(true);
			if(backgroundTime > 30) {
				Intent it = new Intent(this, LoginActivity.class);
				it.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_CLEAR_TOP);
				startActivityForResult(it, 1);			
			}
			stopTime = null;
		}
		super.onStart();
	}
	
	@Override
	protected void onResume() {
		registerRecaiver();
		super.onResume();
	}
	
	@Override
	protected void onStop() {
		LocalBroadcastManager.getInstance(this).unregisterReceiver(receiver);		
		stopTime = new Time();
		stopTime.setToNow();
		super.onStop();
	}
	
	@Override
	protected void onPause() {
		LocalBroadcastManager.getInstance(this).unregisterReceiver(receiver);		
		super.onPause();
	}
	
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		Fragment theFragment = getSupportFragmentManager().findFragmentById(R.id.pager);
		Log.d("FRAGMENT", theFragment.getClass().getSimpleName() );		
		return super.onOptionsItemSelected(item);
	}
	
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.themenu, menu);
        return true;
    }	

	@Override
	public void onTabReselected(Tab tab, FragmentTransaction ft) {
	}

	@Override
	public void onTabSelected(Tab tab, FragmentTransaction ft) {
	}

	@Override
	public void onTabUnselected(Tab tab, FragmentTransaction ft) {
	}
	
	
	
    /**
     * A {@link FragmentPagerAdapter} that returns a fragment corresponding to
     * one of the sections/tabs/pages.
     */
    public class SectionsPagerAdapter extends FragmentPagerAdapter {
    	List<Fragment> theFragments = new ArrayList<Fragment>(4);
    	
        public SectionsPagerAdapter(FragmentManager fm) {
            super(fm);
        }
        
        public Fragment getFragment(int location)
        {
        	return theFragments.get(location);
        }

        @Override
        public Fragment getItem(int position) {
            // getItem is called to instantiate the fragment for the given page.
            // Return a DummySectionFragment (defined as a static inner class
            // below) with the page number as its lone argument.
            Fragment fragment = null;
            
            switch(position)
            {
            	case 0:
            		fragment = new MainActivity();
            		break;
            	case 1:
            		fragment = new BodyActivity();
            		break;
            	case 2:
            		fragment = new ServiceActivity();
            		break;
            	case 3:
            		fragment = new OffersActivity();
            		break;             		
            	default:
            		break;
            }
    		theFragments.add(position, fragment);
            return fragment;
        }

		@Override
		public int getCount() {
			// TODO Auto-generated method stub
			return 4;
		}


    }
	

}

